<route lang="json5" type="page">
{
  style: { navigationBarTitleText: '编辑资料' },
}
</route>

<template>
  <view class="flex flex-col items-center justify-start px-4 py-8 full-screen-120px bg-gray-50">
    <!-- 顶部标题 -->
    <view class="w-full text-left mb-12">
      <text class="text-2xl font-bold text-gray-800">编辑资料</text>
    </view>

    <!-- 表单区域 -->
    <view class="w-full space-y-6">
      <wd-form :model="formModel">
        <wd-cell-group>
          <wd-message-box selector="handleAvatarCellClick" />
          <wd-cell title="头像" size="large" center clickable @click="handleAvatarCellClick">
            <image class="image-avatar-8" :src="determineAvatar" />
          </wd-cell>
          <wd-input
            v-model="formModel.nickname"
            label="昵称"
            label-width="20%"
            prop="nickname"
            placeholder="请输入昵称"
            size="large"
            clearable
            :rules="[{ required: true, message: '请输入昵称' }]"
          />
          <wd-cell title="生日" size="large" center>
            <picker
              mode="date"
              start="1900-01-01"
              :end="textOfToday"
              :value="formModel.birthday"
              @change="handleBirthdayPickerChange"
            >
              <view>{{ formModel.birthday }}</view>
            </picker>
          </wd-cell>
          <wd-cell title="性别" size="large" center>
            <picker
              mode="selector"
              :range="GenderEnumLabels"
              :value="formModel.gender"
              @change="handleGenderPickerChange"
            >
              <view>{{ GenderEnumLabels[formModel.gender] }}</view>
            </picker>
          </wd-cell>
        </wd-cell-group>
      </wd-form>

      <!-- 确认按钮 -->
      <button
        class="w-full py-3 rounded-lg bg-blue-500 text-white font-medium disabled:opacity-50 disabled:cursor-not-allowed"
        @click="handleSubmit"
      >
        确认修改
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {
  getProfileApi,
  updateProfileApi,
  updateProfileAvatarApi,
} from '@/service/me/profile/profileApi'
import {
  AppUserProfileModel,
  GenderEnum,
  GenderEnumLabels,
} from '@/service/me/profile/model/profileModel'
import { useUserStore } from '@/store'
import { dayjs, useMessage } from 'wot-design-uni'

const textOfToday = dayjs().format('YYYY-MM-DD')

const formModel = reactive<AppUserProfileModel>({
  avatar: null,
  nickname: null,
  birthday: null,
  gender: GenderEnum.UNKNOWN,
})
const determineAvatar = computed(function () {
  return formModel.avatar ?? '/static/images/avatar/default.jpg'
})

const message4AvatarCellClick = useMessage('handleAvatarCellClick')
const handleAvatarCellClick = function () {
  message4AvatarCellClick
    .confirm({
      title: '是否更换头像？',
      confirmButtonText: '使用相册图片',
    })
    .then(chooseImage)

  function chooseImage() {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      extension: ['jpg', 'jpeg', 'png', 'webp', 'heic'],
      sourceType: ['album'],
      success: (res) => chooseImageSuccess(res),
    })

    async function chooseImageSuccess(res: UniApp.ChooseImageSuccessCallbackResult) {
      const successFlag = await updateProfileAvatarApi(res.tempFilePaths)
      if (successFlag) {
        uni.showToast({
          title: '设置成功',
        })
        reload()
      }
    }
  }
}

const handleBirthdayPickerChange = function (event) {
  formModel.birthday = event.detail.value
}

const handleGenderPickerChange = function (event) {
  formModel.gender = event.detail.value
}

const handleSubmit = async function () {
  await updateProfileApi(formModel)
  uni.showToast({
    title: '设置成功',
  })
  reload()
}

const reload = async function () {
  const apiResult = await getProfileApi()
  Object.assign(formModel, apiResult.data)

  // 更换本地记录的昵称
  const userStore = useUserStore()
  userStore.userInfo.nickname = formModel.nickname
}

onLoad(() => {
  reload()
})
</script>

<style lang="scss" scoped>
// 空样式，全部复用 UnoCSS
</style>
